package cn.schoolwow.quickdao.module.database.ddl.common.flow;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.List;

public class SaveDatabaseEntityToCacheFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        saveEntity(flowContext);
        saveEntityList(flowContext);
    }

    @Override
    public String name() {
        return "保存数据库表信息到缓存";
    }

    private void saveEntity(FlowContext flowContext){
        Entity entity = (Entity) flowContext.getData("entity");
        if(null==entity){
            return;
        }
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);

        quickDAOConfig.databaseContext.databaseTableCache.put(entity.tableName, entity);
    }

    private void saveEntityList(FlowContext flowContext){
        List<Entity> entityList = (List<Entity>) flowContext.getData("entityList");
        if(null==entityList||entityList.isEmpty()){
            return;
        }
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);

        for(Entity entity:entityList){
            quickDAOConfig.databaseContext.databaseTableCache.put(entity.tableName, entity);
        }
    }

}
